package com.andengine.editor.sceneeditor;

import com.andengine.editor.components.CheckBoxList;
import com.gooddies.swing.Toast;
import com.swingson.SwingsonGui;
import com.swingson.SwingsonGuiBuilder;
import com.swingson.exceptions.ErrorMessageException;
import java.io.File;
import java.io.IOException;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

/**
 * @author sad
 */
public class SceneEditorPanel extends JPanel {

    private ScenePlane plane;
    private final CheckBoxList<Layer> layersList = new CheckBoxList<Layer>();
    private SwingsonGui gui;

    public SceneEditorPanel() throws IOException {
        this.plane = new ScenePlane();
        layersList.addCheckBoxItem(new Layer("default"));
        layersList.addCheckBoxItem(new Layer("Scene"));
        layersList.addCheckBoxItem(new Layer("Aaaa"));
        layersList.addCheckBoxItem(new Layer("nbk"));
        gui = SwingsonGuiBuilder.createGuiFromJsonInPackage("sceneEditor.json", this);
        layersList.setSelectionChangeEvent(new CheckBoxList.OnSelectionChange<Layer>() {

            @Override
            public boolean change(Layer layer, int index, boolean state) {
                if(index==0){
                    return false;
                }
                if (state) {
                    layerShow(layer);
                } else {
                    layerHide(layer);
                }

                return true;
            }
        });
    }

    protected void onLayersPopup(JPopupMenu menu) {
        boolean enable = (layersList.getSelectedIndex() != 0 && layersList.getSelectedIndex() != -1);
        ((JMenuItem) gui.getDefinedComponent("deleteLayerMenu").getComponent()).setEnabled(enable);
    }

    protected void onAddNewLayer() {
        layersList.addCheckBoxItem(new Layer("New Layer"));
    }

    protected void onRemoveLayer() {
        layersList.removeObject(layersList.getSelectedIndex());
    }

    private void layerShow(Layer layer) {
        Toast.makeText(this, "Layer " + layer.getName() + " show", Toast.Style.NORMAL).display();
    }

    private void layerHide(Layer layer) {
        Toast.makeText(this, "Layer " + layer.getName() + " hide", Toast.Style.ERROR).display();
    }

    protected void onSceneSpriteDrop(File file) {
        if (!com.gooddies.utils.FileUtils.getFileExtension(file).toLowerCase().equals("trgn")) {
            throw new ErrorMessageException(file.getAbsolutePath() + " is not texture region file (.trgn)");
        }

        dropTextureRegion(file);
    }

    protected void dropTextureRegion(File textureRegion) {

    }

    protected void onError(Throwable ex) {
        if (ex instanceof ErrorMessageException) {
            Toast.makeText(this, ex.getMessage(), Toast.Style.ERROR).display();
        }
    }
}
